package org.groupg.project.configmanager.ui;


import org.groupg.project.configmanager.model.SshConfig;
import org.groupg.project.configmanager.service.ConfigService;
import org.groupg.project.configmanager.service.SshConnectionService;
import org.groupg.project.configmanager.util.ClipboardUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.List;

/**
 * SSH配置面板，显示和管理SSH配置，支持Ctrl+C复制单元格内容
 */
public class SshConfigPanel extends JPanel {
    private JTable configTable;
    private DefaultTableModel tableModel;
    private JButton addButton, editButton, deleteButton, connectButton, testButton;
    private ConfigService configService;

    public SshConfigPanel() {
        configService = new ConfigService();
        initializeUI();
        loadData();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());

        // 表格
        String[] columnNames = {"ID", "名称", "主机", "端口", "用户名","密码", "认证方式"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        configTable = new JTable(tableModel);

        // 设置行高，便于操作
        configTable.setRowHeight(30);

        // 为表格添加右键复制菜单
        JPopupMenu tableMenu = new JPopupMenu();
        JMenuItem copyCellItem = new JMenuItem("复制单元格内容");
        JMenuItem copyRowItem = new JMenuItem("复制整行数据");
        JMenuItem copyCommandItem = new JMenuItem("复制SSH命令");

        copyCellItem.addActionListener(e -> copySelectedCell());
        copyRowItem.addActionListener(e -> copySelectedRow());
        copyCommandItem.addActionListener(e -> copySshCommand());

        tableMenu.add(copyCellItem);
        tableMenu.add(copyRowItem);
        tableMenu.add(copyCommandItem);
        configTable.setComponentPopupMenu(tableMenu);

        // 添加Ctrl+C快捷键支持
        setupCopyShortcut();

        add(new JScrollPane(configTable), BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        addButton = new JButton("添加");
        editButton = new JButton("编辑");
        deleteButton = new JButton("删除");
        connectButton = new JButton("连接");
        testButton = new JButton("测试连接");

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(connectButton);
        buttonPanel.add(testButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 事件监听
        addButton.addActionListener(e -> showConfigDialog(null));
        editButton.addActionListener(e -> editSelectedConfig());
        deleteButton.addActionListener(e -> deleteSelectedConfig());
        connectButton.addActionListener(e -> connectToSelectedHost());
        testButton.addActionListener(e -> testSelectedConnection());
    }

    /**
     * 设置Ctrl+C快捷键复制功能
     */
    private void setupCopyShortcut() {
        // 创建复制操作
        Action copyAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                copySelectedCell();
            }
        };

        // 将Ctrl+C绑定到复制操作
        KeyStroke copyKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK);
        configTable.getInputMap(JComponent.WHEN_FOCUSED).put(copyKeyStroke, "copy");
        configTable.getActionMap().put("copy", copyAction);

        // 添加工具提示
        configTable.setToolTipText("选中单元格后按 Ctrl+C 复制内容");
    }

    /**
     * 复制选中的单元格内容
     */
    private void copySelectedCell() {
        int selectedRow = configTable.getSelectedRow();
        int selectedColumn = configTable.getSelectedColumn();

        if (selectedRow >= 0 && selectedColumn >= 0) {
            Object value = tableModel.getValueAt(selectedRow, selectedColumn);
            if (value != null) {
                ClipboardUtil.copyToClipboard(value.toString());
                showCopySuccessMessage("已复制: " + value);
            }
        } else {
            // 如果没有选中单元格，尝试复制整行
            copySelectedRow();
        }
    }

    /**
     * 复制选中的整行数据
     */
    private void copySelectedRow() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            StringBuilder rowData = new StringBuilder();
            for (int col = 0; col < tableModel.getColumnCount(); col++) {
                Object value = tableModel.getValueAt(selectedRow, col);
                rowData.append(tableModel.getColumnName(col)).append(": ").append(value);
                if (col < tableModel.getColumnCount() - 1) {
                    rowData.append("\r");
                }
            }
            ClipboardUtil.copyToClipboard(rowData.toString());
            showCopySuccessMessage("已复制整行数据");
        } else {
            showCopySuccessMessage("请先选择要复制的单元格或行");
        }
    }

    /**
     * 显示复制成功消息
     */
    private void showCopySuccessMessage(String message) {
        // 使用状态栏或短暂提示显示消息
        // 这里简单使用控制台输出
        System.out.println(message);
    }

    private void loadData() {
        try {
            List<SshConfig> configs = configService.getAllSshConfigs();
            tableModel.setRowCount(0);
            for (SshConfig config : configs) {
                String authType = (config.getPrivateKeyPath() != null && !config.getPrivateKeyPath().isEmpty()) ?
                        "私钥认证" : (config.getPassword() != null && !config.getPassword().isEmpty()) ? "密码认证" : "无认证";

                tableModel.addRow(new Object[]{
                        config.getId(),
                        config.getName(),
                        config.getHost(),
                        config.getPort() != null ? config.getPort() : 22,
                        config.getUsername(),
                        config.getPassword(),
                        authType
                });
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showConfigDialog(SshConfig config) {
        SshConfigDialog dialog = new SshConfigDialog((Frame) SwingUtilities.getWindowAncestor(this), config);
        dialog.setVisible(true);
        if (dialog.isSaved()) {
            try {
                configService.saveSshConfig(dialog.getConfig());
                loadData();
                JOptionPane.showMessageDialog(this, "配置保存成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void editSelectedConfig() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
            try {
                SshConfig config = configService.getAllSshConfigs().stream()
                        .filter(c -> c.getId().equals(id))
                        .findFirst()
                        .orElse(null);
                if (config != null) {
                    showConfigDialog(config);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "加载配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要编辑的配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void deleteSelectedConfig() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            int result = JOptionPane.showConfirmDialog(this, "确定要删除选中的配置吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
                try {
                    configService.deleteSshConfig(id);
                    loadData();
                    JOptionPane.showMessageDialog(this, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void connectToSelectedHost() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
            try {
                SshConfig config = configService.getAllSshConfigs().stream()
                        .filter(c -> c.getId().equals(id))
                        .findFirst()
                        .orElse(null);

                if (config != null) {
                    try {
                        // 显示连接信息
                        int result = JOptionPane.showConfirmDialog(
                                this,
                                config.getConnectionInfo() + "\n\n是否立即连接？",
                                "SSH连接确认",
                                JOptionPane.YES_NO_OPTION
                        );

                        if (result == JOptionPane.YES_OPTION) {
                            SshConnectionService.connectToSsh(config);
                            JOptionPane.showMessageDialog(this,
                                    "正在启动SSH连接...\n命令: " + config.generateSshCommand(),
                                    "连接启动",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(this,
                                "连接失败: " + e.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "加载配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要连接的SSH配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void testSelectedConnection() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
            try {
                SshConfig config = configService.getAllSshConfigs().stream()
                        .filter(c -> c.getId().equals(id))
                        .findFirst()
                        .orElse(null);

                if (config != null) {
                    boolean isReachable = SshConnectionService.testSshConnection(config);
                    if (isReachable) {
                        JOptionPane.showMessageDialog(this,
                                "主机 " + config.getHost() + " 可达，可以连接",
                                "测试成功",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(this,
                                "无法连接到主机 " + config.getHost(),
                                "测试失败",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "加载配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要测试的SSH配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void copySshCommand() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
            try {
                SshConfig config = configService.getAllSshConfigs().stream()
                        .filter(c -> c.getId().equals(id))
                        .findFirst()
                        .orElse(null);

                if (config != null) {
                    String sshCommand = config.generateSshCommand();
                    ClipboardUtil.copyToClipboard(sshCommand);
                    JOptionPane.showMessageDialog(this,
                            "已复制SSH命令到剪贴板:\n" + sshCommand,
                            "复制成功",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "加载配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要复制命令的SSH配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}